#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QStyleOption>
#include <QDebug>
#include "skpoint.h"
#include "skline.h"
#include "skscene.h"


SkPoint::SkPoint(const int& id,const QPointF& point,const qreal& radius,QGraphicsItem * parent):
        QGraphicsItem(parent),SkIdAble(id),newPos(point),skRadius(radius)
{
    setPos(point);
    setFlag(ItemIsMovable);
    setCacheMode(DeviceCoordinateCache);
    setZValue(-1); // linie i circle na -2
}
void SkPoint::addLine(SkLine *line){
    linesList << line;
    line->adjust();
}
QList<SkLine *> SkPoint::lines() const{
    return linesList;
}
bool SkPoint::advance(){

    if (newPos == pos())
        return false;

    setPos(newPos);
    return true;
}

QRectF SkPoint::boundingRect() const{

    return QRectF(-skRadius/2, -skRadius/2, skRadius,skRadius);
}
QPainterPath SkPoint::shape() const{
    QPainterPath path;
    path.addEllipse(boundingRect());
    return path;
}
void SkPoint::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
	Q_UNUSED(widget);
    QRadialGradient gradient(-skRadius/2, -skRadius/2, skRadius*2);
    if (option->state & QStyle::State_Sunken) {
        gradient.setColorAt(1, QColor(Qt::green).light(120));
        gradient.setColorAt(0, QColor(Qt::darkGreen).light(120));
    } else {
        gradient.setColorAt(0, Qt::yellow);
        gradient.setColorAt(1, Qt::darkYellow);
    }
    painter->setBrush(gradient);
    painter->setPen(QPen(Qt::black, 0));
    painter->drawEllipse(QRectF(-skRadius/2,-skRadius/2,skRadius,skRadius));

}

QVariant SkPoint::itemChange(GraphicsItemChange change, const QVariant &value){

    switch (change) {
    case ItemPositionHasChanged:
        foreach (SkLine *line, linesList)
            line->adjust();
        break;
    default:
        break;
    };

    return QGraphicsItem::itemChange(change, value);
}
void SkPoint::mousePressEvent(QGraphicsSceneMouseEvent *event){
    update();
    QGraphicsItem::mousePressEvent(event);
}

void SkPoint::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){
    update();
    if(event->button()==Qt::RightButton){
        ((SkScene*)scene())->pointClicked(getSkId());
//        qDebug() << "Right";
    }else{
        ((SkScene*)scene())->pointPosChanged(getSkId(),pos());
        QGraphicsItem::mouseReleaseEvent(event);
    }

}

qreal SkPoint::radius() const{
    return skRadius;
}
